package com.warningrc.system.data.dao;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.warningrc.system.Constants;

/**
 * @author <a href="http://weibo.com/weibowarning">王宁</a>
 * @date 2011-12-30
 * @email <a href="mailto:childe.wangning@gmail.com">childe.wangning@gmail.com</a>
 * @param <T>
 */
public class GenericDaoHibernateImpl<T> extends HibernateDaoSupport implements
		GenericDao<T> {
	protected Class<T> entityClass;

	private static final String QUERY_STRING = " FROM {0} ";

	public GenericDaoHibernateImpl(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	@Override
	public Serializable create(T newInstance) {
		return getHibernateTemplate().save(newInstance);
	}

	@Override
	public void delete(T transientObject) {
		getHibernateTemplate().delete(transientObject);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T read(Serializable id) {
		return (T) getHibernateTemplate().get(entityClass, id);
	}

	@SuppressWarnings( { "static-access", "unchecked" })
	@Override
	public List<T> read(int start, int count) {
		Query query = getSession().createQuery(
				Constants.MESSAGEFORMAT.format(QUERY_STRING, entityClass
						.getName())).setFirstResult(start).setMaxResults(count);
		return query.list();
	}

	@Override
	public void update(T transientObject) {
		getHibernateTemplate().update(transientObject);
	}

	@SuppressWarnings( { "static-access", "unchecked" })
	@Override
	public List<T> readAll() {
		return getHibernateTemplate().find(
				Constants.MESSAGEFORMAT.format(QUERY_STRING, entityClass
						.getName()));
	}

	@Override
	public String toString() {
		return "GenericDaoHibernateImpl [entityClass=" + entityClass + "]";
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> read(String queryString) {
		return getHibernateTemplate().find(queryString);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> read(String queryString, Map<String, Object> param) {
		Query query = this.getSession().createQuery(queryString);
		// 设置查询事务超时时间
		SessionFactoryUtils.applyTransactionTimeout(query, getSessionFactory());
		for (String key : param.keySet()) {
			query.setParameter(key, param.get(key));
		}
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> read(String queryString, String paramName, Object paramValue) {
		Query query = this.getSession().createQuery(queryString);
		// 设置查询事务超时时间
		SessionFactoryUtils.applyTransactionTimeout(query, getSessionFactory());
		query.setParameter(paramName, paramValue);
		return query.list();
	}
}
